package vg.services.graph_layout_manager;

import com.google.common.collect.Lists;
import vg.services.graph_layout_manager.interfaces.IGraphLayout;
import vg.services.graph_layout_manager.interfaces.IGraphLayoutManager;
import vg.services.graph_layout_manager.realization.jgraph_layout.*;
import vg.services.graph_layout_manager.realization.jgraph_layout.smart_graph_layout.SmartGraphLayout;
import vg.services.main_manager.VGMainServiceHelper;

import java.util.List;

public class GraphLayoutManager implements IGraphLayoutManager {
	// Main data
	private List<IGraphLayout> layouts = Lists.newArrayList();
	private IGraphLayout currentLayout = null;
	
	// Mutex
	private final Object generalMutex = new Object();

	public GraphLayoutManager() {
		// install jgraph layouts
        registerLayout(new HierarchicalLayout());
        registerLayout(new LayeredLayout());
        registerLayout(new FastOrganicLayout());
        registerLayout(new CircleLayout());
        registerLayout(new CompactTreeLayout());
        registerLayout(new OrganicLayout());
        registerLayout(new PartitionLayout());
        registerLayout(new SmartGraphLayout());
    }
	
	@Override
	public void registerLayout(IGraphLayout layout) {
		if (layout == null) return;
		
		synchronized (generalMutex) {
			layouts.add(layout);
			if (currentLayout == null)
				currentLayout = layout;
			
			String name1 = layout.getName();
			String name2 = VGMainServiceHelper.config.getProperty(DEF_CURRENT_LAYOUT);
			if (name2 == null) {
                VGMainServiceHelper.config.setProperty(DEF_CURRENT_LAYOUT, name1);
				name2 = name1;
			}
			if (name1 != null && name1.equals(name2)) {
				currentLayout = layout;
			}
		}
	}
	
	@Override
	public List<IGraphLayout> getInstalledLayouts() {
		synchronized (generalMutex) {
			return Lists.newArrayList(layouts);
		}
	}
	
	@Override
	public void setCurrentLayout(IGraphLayout layout) {
		if (layout == null) return;
		
		synchronized (generalMutex) {
			this.currentLayout = layout;
			
			String name = layout.getName();
            VGMainServiceHelper.config.setProperty(DEF_CURRENT_LAYOUT, name);
		}
	}
	
	@Override
	public IGraphLayout getCurrentLayout() {
		synchronized (generalMutex) {
			return currentLayout;
		}
	}
}
